package com.gamerank.web.action.score;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.stereotype.Controller;

import com.gamerank.bean.GameRankInfo;
import com.gamerank.bean.PageView;
import com.gamerank.bean.QueryResult;
import com.gamerank.service.score.GameRankService;
import com.gamerank.web.formbean.score.GameRankInfoForm;
import com.google.gson.Gson;

@Controller("/admin/gamerank")
public class GameRankAction extends DispatchAction {

	@Resource(name = "gameRankServiceImpl")
	private GameRankService service;

	private Gson gson = new Gson();

	public ActionForward testJson(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<GameRankInfo> list = new ArrayList<GameRankInfo>();
		GameRankInfo tb = new GameRankInfo();
		tb.setId(100);
		tb.setGameName("duckGame");
		tb.setGameScore(3500);
		tb.setDeviceId("0011");
		tb.setDeviceSoftVersion("2.3");
		tb.setPhoneNumber("135-1234-5678");
		list.add(tb);

		this.outputJSon(response, list);

		return null;
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		QueryResult<GameRankInfo> qr = service
				.getScrollData(GameRankInfo.class);
		this.outputJSon(response, qr);
		return null;
	}

	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		GameRankInfo gameRankInfo = new GameRankInfo();
		gameRankInfo.setGameName(formBean.getGameName());
		gameRankInfo.setUserName(formBean.getUserName());
		gameRankInfo.setGameScore(formBean.getGameScore());
		gameRankInfo.setDeviceId(formBean.getDeviceId());
		gameRankInfo.setPhoneNumber(formBean.getPhoneNumber());
		gameRankInfo.setDeviceSoftVersion(formBean.getDeviceSoftVersion());
		gameRankInfo.setCount(1);
		gameRankInfo.setDate(new Date());
		gameRankInfo.setRequestIP(request.getRemoteAddr());
		gameRankInfo.setPlayCount(1);
		service.save(gameRankInfo);
		request.setAttribute("message", "save score OK!");
		request.setAttribute("urladdress", "gamerank.do?method=listAll");
		return mapping.findForward("message");
	}

	public ActionForward addScoreUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("addScoreUI");
	}

	public ActionForward getTOP5(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
		orderBy.put("gameScore", "desc");
		QueryResult<GameRankInfo> qr = service.getScrollData(
				GameRankInfo.class, 0, 5, orderBy);
		this.outputJSon(response, qr);
		return null;
	}

	public ActionForward getMyGameRank(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		HashMap<String, Object> where = new HashMap<String, Object>();
		where.put("deviceId=", formBean.getDeviceId());
		where.put("gameName=", formBean.getGameName());
		QueryResult<GameRankInfo> qr = service.getScrollData(
				GameRankInfo.class, where);
		this.outputJSon(response, qr);
		return null;
	}

	public ActionForward queryMyScoreUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("queryMyScoreUI");
	}

	private void outputJSon(HttpServletResponse response, Object list) {
		response.setContentType("application/json; charset=GBK");// Chinese
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.write(gson.toJson(list));
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ActionForward listAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		PageView<GameRankInfo> pageView = new PageView<GameRankInfo>(12,
				formBean.getPage());
		int firstIndex = (pageView.getCurrentpage() - 1)
				* pageView.getMaxresult();
		QueryResult<GameRankInfo> qr = service.getScrollData(
				GameRankInfo.class, firstIndex, pageView.getMaxresult());
		pageView.setQueryResult(qr);
		request.setAttribute("pageView", pageView);
		return mapping.findForward("listAllUI");
	}

	public ActionForward editScoreUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		GameRankInfo rank = service.query(GameRankInfo.class, formBean.getId());
		formBean.setId(rank.getId());
		formBean.setDeviceId(rank.getDeviceId());
		formBean.setDeviceSoftVersion(rank.getDeviceSoftVersion());
		formBean.setGameName(rank.getGameName());
		formBean.setGameScore(rank.getGameScore());
		formBean.setPhoneNumber(rank.getPhoneNumber());
		formBean.setUserName(rank.getUserName());
		return mapping.findForward("editScoreUI"); // JSP
	}

	public ActionForward editScore(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		GameRankInfo gameRankInfo = service.query(GameRankInfo.class,
				formBean.getId());
		gameRankInfo.setGameName(formBean.getGameName());
		gameRankInfo.setUserName(formBean.getUserName());
		gameRankInfo.setGameScore(formBean.getGameScore());
		gameRankInfo.setDeviceId(formBean.getDeviceId());
		gameRankInfo.setPhoneNumber(formBean.getPhoneNumber());
		gameRankInfo.setDeviceSoftVersion(formBean.getDeviceSoftVersion());
		gameRankInfo.setCount(gameRankInfo.getCount() + 1);
		gameRankInfo.setDate(new Date());
		service.update(gameRankInfo);
		request.setAttribute("message", "edit score OK!");
		request.setAttribute("urladdress", "gamerank.do?method=listAll");
		return mapping.findForward("message");
	}

	public ActionForward delScore(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		service.delete(GameRankInfo.class, formBean.getId());
		request.setAttribute("message", "Del score OK!");
		request.setAttribute("urladdress", "gamerank.do?method=listAll");
		return mapping.findForward("message");
	}

	public ActionForward queryMyRankingUI(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return mapping.findForward("queryMyRankingUI");
	}

	public ActionForward getScoreRanking(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		String score = "";
		GameRankInfo info = queryOneRankInfo(formBean.getDeviceId(),
				formBean.getGameName());
		if (info != null) {
			score += info.getGameScore();
		}
		int ranking = service.getRanking(formBean.getGameName(),
				formBean.getDeviceId());
		this.outputJSon(response, score + " / " + ranking);
		return null;
	}

	private GameRankInfo queryOneRankInfo(String devID, String gameName) {
		HashMap<String, Object> where = new HashMap<String, Object>();
		where.put("deviceId=", devID);
		where.put("gameName=", gameName);
		QueryResult<GameRankInfo> qr = service.getScrollData(
				GameRankInfo.class, where);
		if (null != qr) {
			List<GameRankInfo> qrList = qr.getResultList();
			if (qrList != null && qrList.size() > 0) {
				return (GameRankInfo) qrList.get(0);
			}
		}
		return null;
	}

	
	public ActionForward updatePlayCountUI(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return mapping.findForward("updatePlayCountUI");
	}
	
	public ActionForward updatePlayCount(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		GameRankInfoForm formBean = (GameRankInfoForm) form;
		GameRankInfo gameRankInfo = queryOneRankInfo(formBean.getDeviceId(),
				formBean.getGameName());
		if (gameRankInfo != null) {
			gameRankInfo.setPlayCount(gameRankInfo.getPlayCount() + 1);
			gameRankInfo.setDate(new Date());
			service.update(gameRankInfo);
			request.setAttribute("message", "Update play count OK!");
			request.setAttribute("urladdress", "gamerank.do?method=listAll");
			return mapping.findForward("message");
		} 
		return null;
	}
}
